package com.uber.notes.model.data;


import android.os.Bundle;
import android.preference.PreferenceManager;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.common.collect.Lists;


import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
//import android.accounts.AuthenticatorException;
//import android.accounts.OperationCanceledException;
import android.app.Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

public class GoogleData {

	// private Activity activity;

		/** Logging level for HTTP requests/responses. */
		private static Level LOGGING_LEVEL = Level.CONFIG;

		private static final String AUTH_TOKEN_TYPE = "cl";

		private static final int REQUEST_AUTHENTICATE = 0;


		final HttpTransport transport = AndroidHttp.newCompatibleTransport();

		private static final String PREF_ACCOUNT_NAME = "calendarbegeleider1@gmail.com";
		private static final String PREF_SELECTED_CAL_LINK = "selectedCalendarFeed";
		private static final String PREF_AUTH_TOKEN = "authToken";
		private static final String PREF_GSESSIONID = "gsessionid";

		private GoogleAccountManager accountManager;
		private SharedPreferences settings;
		private CalendarAndroidRequestInitializer requestInitializer;

		static String accountName;
		private Activity activity;

		private boolean bool = false;

		/**
		 * 
		 * @author H4nt3r
		 * 
		 */
		public class CalendarAndroidRequestInitializer extends
				CalendarRequestInitializer {

			String authToken;

			public CalendarAndroidRequestInitializer() {
				super(transport);
				Log.v("Test log", "CalendarAndroidRequestInitializer");
				authToken = settings.getString(PREF_AUTH_TOKEN, null);
				setGsessionid(settings.getString(PREF_GSESSIONID, null));
			}

			@Override
			public void intercept(HttpRequest request) throws IOException {
				super.intercept(request);
				// Log.v("Test log", "intercept");
				request.getHeaders().setAuthorization(
						GoogleHeaders.getGoogleLoginValue(authToken));
			}

			@Override
			public boolean handleResponse(HttpRequest request,
					HttpResponse response, boolean retrySupported)
					throws IOException {
				switch (response.getStatusCode()) {
				case 302:
					super.handleResponse(request, response, retrySupported);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString(PREF_GSESSIONID, getGsessionid());
					editor.commit();
					return true;
				case 401:
					accountManager.invalidateAuthToken(authToken);
					authToken = null;
					SharedPreferences.Editor editor2 = settings.edit();
					editor2.remove(PREF_AUTH_TOKEN);
					editor2.commit();
					return false;
				}
				return false;
			}
		}

		/**
		 * 
		 * @param activity
		 */
		public GoogleData(Activity activity) {
			doShizlAtStartup();
			
			Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);

			this.activity = activity;

			accountManager = new GoogleAccountManager(activity);

			settings = PreferenceManager.getDefaultSharedPreferences(activity
					.getApplication());

			requestInitializer = new CalendarAndroidRequestInitializer();


			Account[] accounts = accountManager.getAccounts();
			
			for(int i = 0; i < accounts.length; i++){
				Log.v("UBERNOTES", "acc: " + accounts[i].name);
			}
			
			gotAccount();
			
			//client = new CalendarClient(requestInitializer.createRequestFactory());
			//client.setPrettyPrint(true);
			//client.setApplicationName("Google-CalendarAndroidSample/1.0");
		}

		public void setRequestInitNull() {
			requestInitializer.authToken = null;
		}

		
		private void doShizlAtStartup(){
			accountName = PREF_ACCOUNT_NAME;
		}
		/*
		 * 
		 */
		public boolean gotAccount() {
			bool = false;

			//accountName = settings.getString(PREF_ACCOUNT_NAME, null);
			
			Account account = accountManager.getAccountByName(accountName);

			// handle invalid token
			if (requestInitializer.authToken == null) {
				Log.v("Test Class", "requestInit authToken == null");
				accountManager.manager.getAuthToken(account, AUTH_TOKEN_TYPE, true,
						new AccountManagerCallback<Bundle>() {
							public void run(AccountManagerFuture<Bundle> future) {
								try {
									Bundle bundle = future.getResult();
									if (bundle
											.containsKey(AccountManager.KEY_INTENT)) {
										// toestemming vragen of de app de
										// account
										// wilt gebruiken.

										Toast toast = Toast.makeText(
												activity.getApplicationContext(),
												"Toestemming vragen gestart",
												Toast.LENGTH_SHORT);
										toast.show();

										Intent intent = bundle
												.getParcelable(AccountManager.KEY_INTENT);
										int flags = intent.getFlags();
										flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
										intent.setFlags(flags);

										activity.startActivityForResult(intent,
												REQUEST_AUTHENTICATE);

										bool = false;
									} else if (bundle
											.containsKey(AccountManager.KEY_AUTHTOKEN)) {
										setAuthToken(bundle
												.getString(AccountManager.KEY_AUTHTOKEN));
										bool = false;
									}
								} catch (Exception e) {
									Log.v("e", "e");
									handleException(e);
								}
							}
						}, null);
			} else {
				bool = true;
			}
			return bool;
		}

		/**
		 * 
		 * @param authToken
		 */
		void setAuthToken(String authToken) {

			SharedPreferences.Editor editor = settings.edit();
			editor.putString(PREF_AUTH_TOKEN, authToken);
			editor.commit();
			requestInitializer.authToken = authToken;

			Toast toast = Toast.makeText(activity.getApplicationContext(),
					"Toestemming verwerkt, klik op de account om door te gaan",
					Toast.LENGTH_SHORT);
			toast.show();
		}

		/**
		 * 
		 * @param e
		 */
		void handleException(Exception e) {
			Log.v("Test log methode", "handleException");
			e.printStackTrace();
			if (e instanceof HttpResponseException) {
				HttpResponse response = ((HttpResponseException) e).getResponse();
				int statusCode = response.getStatusCode();
				try {
					response.ignore();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				// TODO(yanivi): should only try this once to avoid infinite loop
				if (statusCode == 401) {
					gotAccount();
					return;
				}
				try {
					Log.e("planaid", response.parseAsString());
				} catch (IOException parseException) {
					parseException.printStackTrace();
				}
			}
			Log.e("planaid", e.getMessage(), e);
		}



		/*
		public List<CalendarEntry> getCalendars() {
			if (gotAccount()) {
				List<CalendarEntry> calendars = Lists.newArrayList();
				calendars.clear();
				try {
					CalendarUrl url = forAllCalendarsFeed();

					// page through results
					while (true) {
						CalendarFeed feed = client.calendarFeed().list()
								.execute(url);
						if (feed.calendars != null) {
							calendars.addAll(feed.calendars);
						}
						String nextLink = feed.getNextLink();
						if (nextLink == null) {
							break;
						}
					}

					// op deze manier kan je er door heen itereren.
					String[] calendarNames;
					int numCalendars = calendars.size();
					calendarNames = new String[numCalendars];
					for (int i = 0; i < numCalendars; i++) {
						Log.v("------", "------------------");
						calendarNames[i] = calendars.get(i).title;
						Log.v("--- title ---", calendars.get(i).title);
						// Log.v("--- edit Link ---",
						// calendars.get(i).getEditLink());

						// if(calendars.get(i).summary == null) {
						// Log.v("--- edit summary ---", "NULL");
						// } else {
						// Log.v("--- edit summary ---", calendars.get(i).summary);
						// }

						// Log.v("--- event feed link ---",
						// calendars.get(i).getEventFeedLink());

						if (calendars.get(i).getCalendarAccesListLink() != null) {

							CalendarUrl linkje = new CalendarUrl(calendars.get(i)
									.getCalendarAccesListLink());

							//Log.v("URL",calendars.get(i).getCalendarAccesListLink());
							
							List<AclEntry> alcList = Lists.newArrayList();

							AclFeed aclFeed = client.AlcFeed().list().execute(linkje);

							if (aclFeed.entries != null) {
								alcList.addAll(aclFeed.entries);

								int number = alcList.size();

								Log.v(">-<","" + number);

								if(number > 0) {
									
									///
									for (int x = 0; x < number; x++) {
										AclEntry aclEntry = alcList.get(x);
										Log.v("--- BLAAAAAAT ---", aclEntry.title + "");
										Log.v("--- SCHOEN ---", aclEntry.id + "");
										
										if(aclEntry.AlcScope != null) {
											Log.v("--- HOERAA ---", aclEntry.AlcScope.toString() + "");
										} else {
											Log.v("--- HOERAA ---", "MEh");	
										}
									}
									
//									if(calendars.get(i).title.equals("Test deel agenda"))
//									{
	//
//									}
								}
								
								//AclEntry aclEntry = (AclEntry) alcList.get(0);
								
								//Log.v("--- BLAAAAAAT ---", aclEntry.permissions() + "");
								//Log.v("--- iets summary ---", aclEnt);
								// events.get(x).content + "");
								// Log.v("--- iets etag ---", events.get(x).etag +
								// "");

								// for(AclEntry aclEntry : aclFeed.getEntries()) {
								// System.out.println("\t\tScope: Type=" +
								// aclEntry.getScope().getType() +
								// " (" + aclEntry.getScope().getValue() + ")");
								// System.out.println("\t\tRole: " +
								// aclEntry.getRole().getValue());
								// }

							}

						}
					}

					Log.v("EINDE", "EINDE");

					return calendars;
				} catch (IOException e) {
					handleException(e);
					// calendarNames = new String[] { e.getMessage() };
					calendars.clear();
				}
			}

			return null;
		}
*/
}

